<template>
    <!-- <eui-background type="common"> -->
    <eui-page-frame :topHeight="250" :bottomHeight="90" :withOutBorder="true">
        <template #top>
            <eui-navbar ref="EuiNavBar" :title="title" :storeName="getRelatedName('rdsStores', sUserStore)"
                :storeId="sUserStore" :displayable="true" color="#000000" backgroundColor="#FFFFFF">
                <template v-slot:popupContent>
                    <view class="custom-menu">
                        <view class="setting-item">
                            <eui-card-input v-model="inputMode" title="录入方式" @input="toggleMode" type="radio"
                                :range="inputModeRange" />
                        </view>
                    </view>
                    <view class="setting-desc">
                        <ul style="margin: 2em;padding: 0em">
                            <li>说明
                                <ul style="margin: 0.5em;padding: 0em">
                                    <li>见物扫物：扫描商品条码，数量根据含量自动累加</li>
                                    <li>录入数量：扫物后自动弹框，手动录入商品数量</li>
                                </ul>
                            </li>
                        </ul>
                    </view>
                </template>
            </eui-navbar>
            <view class="top-view">
                <eui-search-bar ref="RdsSearchBar" placeholder="请输入商品编码、条码" @confirm="searchConfirm"
                    v-model="searchText" radius="30" :focus="true" />
            </view>
        </template>
        <eui-page-content>
            <view class="footer-view">
                <eui-card title="基本信息" showTitleLine="true" h-padding="20" type="upDownSingle">
                    <template #content>
                        <eui-card-input style="padding: 16rpx 0rpx;" v-model="mainData.c_wno" title="目的仓库"
                            :name="getRelatedName('rdsWnos', mainData.c_wno)" type="textname"
                            @iconClick="clickRight('c_wno')" required="true"
                            :rightIconType="detailData.length > 0 ? '' : 'right'" />
                        <eui-card-input style="padding: 16rpx 0rpx;" v-model="mainData.c_rec_store_id" type="textname"
                            title="收货机构" :name="getRelatedName('rdsStores', mainData.c_rec_store_id)"
                            v-if="mainData.c_d_type === '2'" />
                        <!-- <eui-text v-model="mainData.c_rec_wno" type="titlename" title="收货仓库"
                            :name="getRelatedName('rdsWnos', mainData.c_rec_wno)" /> -->
                        <!-- <eui-text v-model="mainData.c_rec_store_id" title="收货机构" type="" />
                         -->
                        <!-- <eui-card-input v-model="mainData.c_adno" title="部门" name="rdsDeparts"
                            type="textname" /> -->
                        <eui-card-input style="padding: 16rpx 0rpx;" v-model="mainData.c_rec_wno" title="收货仓库"
                            :name="getRelatedName('rdsWnos', mainData.c_rec_wno)" type="textname"
                            v-if="mainData.c_d_type === '2'" />
                        <eui-card-input style="padding: 16rpx 0rpx;" v-model="mainData.c_provider" title="供应商"
                            :name="getRelatedName('rdsProviders', mainData.c_provider)" type="textname" required="true"
                            :displayable="detailData.length > 0" :rightIconType="detailData.length > 0 ? '' : 'right'"
                            @iconClick="clear" singleTag="c_provider" />
                        <eui-card-input style="padding: 16rpx 0rpx;" v-model="mainData.c_con_no" title="合同号" type="name"
                            displayable="true" />
                    </template>
                    <view class="m-main-top">
                        <eui-text v-model="c_n_rec_total" type="price" title="已收正品数量" />
                        <eui-text v-model="c_sku_rec_total" type="name" title="已收品种数" />
                        <eui-text v-model="c_n_rec_free_total" type="price" title="已收赠品数量" />
                    </view>
                </eui-card>
                <eui-card title="商品验收" showTitleLine="true" h-padding="20" type="detail">
                    <eui-swipe-action>
                        <view v-for="(item, index) in detailData" :key="index" @click="onClickGdsInfo(item, index)"
                            style="background-color:#ffffff">
                            <eui-swipe-actionitem :right-options="options"
                                :disabled="mainData.c_status !== '0' || mainData.c_approve_status !== '1'" show="none"
                                :auto-close="true" @change="change" @click="bindClick($event, index)">
                                <view class="m-list-top">
                                    <eui-text :value="`[${item.c_gcode}]${item.c_gname}`" type="name"
                                        :title="`${index + 1}. 商品`" occupy />
                                    <eui-text v-model="item.c_barcode" type="name" title="条码" />
                                    <eui-text v-model="item.c_order_pack" type="slash" :name="item.c_order_unit"
                                        title="包装/单位" />
                                    <eui-text v-if="sysConfig.inputType === '1'" v-model="item.c_n_pack" type="price" title="件数" />
                                    <eui-text v-if="sysConfig.inputType === '1'" v-model="item.c_n_odd" type="price" title="零数" />
                                    <eui-text v-if="sysConfig.inputType === '2'" v-model="item.c_n_input" type="price" title="包装数" :precision='3' />
                                    <eui-text v-model="item.c_n" type="price" title="收货数量" :precision='3' />
                                    <eui-text v-model="item.c_n_free" type="price" title="赠品数量" :precision='3' />
                                    <eui-text v-model="item.c_product_dt" type="date" title="生产日期" />
                                    <eui-text v-model="item.c_expired_dt" type="date" title="限用日期" />
                                    <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name"
                                        v-if="item.c_err_msg" title="错误" style="white-space: pre-wrap;color: red;"
                                        occupy />
                                </view>
                            </eui-swipe-actionitem>
                        </view>
                    </eui-swipe-action>
                    <view v-if="detailData.length === 0">
                        <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
                        <view class="no-data-text">暂无数据</view>
                    </view>
                </eui-card>
            </view>
        </eui-page-content>
        <template #bottom>
            <view class="bt-button">
                <eui-button type="max" single-tag="submit" title="保存" :disabled="mainData.c_status !== '0'"
                    @buttonClick="buttonClick" />
                <eui-button type="max" single-tag="audit" title="审核" :disabled="mainData.c_status !== '0'"
                    @buttonClick="buttonClick" />
            </view>
        </template>
    </eui-page-frame>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
        <view class="popup-content">
            <view class="popup-title">{{ mainData.c_status === '0' ? '编辑' : '详情' }}</view>
            <view class="m-list-top">
                <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name" title="商品" occupy />
                <eui-text v-model="currentGds.c_barcode" type="name" title="条码" />
                <eui-text v-model="currentGds.c_adno" type="titlename" title="部门"
                    :name="getRelatedName('rdsDeparts', currentGds.c_adno)" />
                <!-- <eui-text v-model="currentGds.c_ccode" type="titlename" title="品类"
                        :name="getRelatedName('rdsGdsclasses', currentGds.c_ccode)" /> -->
                <eui-text :value="getRelatedName('rdsGdsclasses', currentGds.c_ccode)" type="name" title="品类" />
                <eui-text v-model="currentGds.c_bcode" type="titlename" title="品牌"
                    :name="getRelatedName('rdsBrands', currentGds.c_bcode)" />
                <eui-text v-model="currentGds.c_order_pack" type="slash" :name="currentGds.c_order_unit"
                    title="包装/单位" />
                <eui-text :value="currentGds.c_od_day + getDictName('保质期单位', currentGds.c_od_unit)" type="name"
                    title="保质期" />
                <eui-text v-model="currentGds.c_price" type="price" title="售价" />
                <eui-text v-model="currentGds.c_at_pay" type="price" title="结算额" />
                <eui-text :value="currentGds.c_n_pack" type="price" title="件数"
                    v-if="(sysConfig.inputType === '1') && (!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1'))" />
                <eui-text :value="currentGds.c_n_odd" type="price" title="零数"
                    v-if="(sysConfig.inputType === '1') && (!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1'))" />
                <eui-text :value="currentGds.c_n_input" type="price" title="包装数" :precision="3"
                      v-if="(sysConfig.inputType === '2') && (!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1'))" />
            </view>
            <view class="m-list-top" v-if="mainData.c_status !== '0'">
                <eui-text v-model="currentGds.c_n" type="price" title="收货数量" :precision="3" />
                <eui-text v-model="currentGds.c_n_free" type="price" title="赠品数量" :precision="3" />
                <eui-text v-model="currentGds.c_product_dt" type="date" title="生产日期" />
                <eui-text v-model="currentGds.c_expired_dt" type="date" title="限用日期" />
                <eui-text v-model="currentGds.c_serial_no" type="name" title="批号" />
            </view>
            <view v-if="mainData.c_status === '0'">
                <eui-card-input v-model="currentGds.c_n_pack" title="件数" type="number" isBlur fieldName="c_n_pack"
                    @confirm="validateDetail" ref="cardNPackInput" placeholder="请输入件数"
                    v-if="currentGds.c_order_pack > 1 && sysConfig.inputType === '1'" id="c_n_pack" />
                <eui-card-input v-model="currentGds.c_n_odd" title="零数" type="number" isBlur fieldName="c_n_odd"
                    @confirm="validateDetail" ref="cardNOddInput" placeholder="请输入零数"
                    v-if="currentGds.c_order_pack > 1 && sysConfig.inputType === '1'" id="c_n_odd" />
                <eui-card-input v-model="currentGds.c_n_input" title="包装数" type="number" isBlur fieldName="c_n_input"
                    @confirm="validateDetail" ref="cardNIptInput" placeholder="请输入包装数"
                    v-if="currentGds.c_order_pack > 1 && sysConfig.inputType === '2'" id="c_n_input" />
                <eui-card-input id="c_n" v-model="currentGds.c_n" type="number" title="收货数量" fieldName="c_n"
                    @confirm="validateDetail" ref="cardNInput" isBlur required maxlength="9" :focus="true" />
                <eui-card-input id="c_n_free" v-model="currentGds.c_n_free" type="number" title="赠品数量"
                    fieldName="c_n_free" required isBlur @confirm="validateDetail" ref="cardNFreeInput" maxlength="9" />
                <eui-card-input id="c_serial_no" v-model="currentGds.c_serial_no" title="批号/串码" type="text"
                    maxlength="30" />
                <eui-card-input v-model="currentGds.c_product_dt" type="date" @input="productDtChanged" title="生产日期"
                    ref="productDtRef" rightIconType="clear" @iconClick="clear" singleTag="c_product_dt" />
                <eui-card-input v-model="currentGds.c_expired_dt" type="date" @input="expiredDtChanged" title="限用日期"
                    ref="expiredDtRef" rightIconType="clear" @iconClick="clear" singleTag="c_expired_dt" />
                <eui-card-input id="c_pt_pay" v-model="currentGds.c_pt_pay" title="结算价" type="number" isBlur
                    @confirm="validateDetail" ref="cardPtPayInput" fieldName="c_pt_pay" maxlength="9" />
            </view>
        </view>
        <view class="bt-button">
            <eui-button type="max" single-tag="cancel" title="关闭" @buttonClick="buttonClick" />
            <eui-button type="max" single-tag="submit3" title="确认" :disabled="mainData.c_status !== '0'"
                @buttonClick="buttonClick" />
        </view>
    </eui-popup>
    <eui-popup ref="providerPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
        <view class="popup-content">
            <view class="popup-title">选择供应商</view>
            <scroll-view :scroll-top="0" scroll-y="true">
                <view v-for="(item, index) in providerList" :key="index" @click="clickProviderInfo(item, index)">
                    <view class="m-list-top">
                        <eui-text :value="item" type="name" :title="`${1 + index}. 供应商编码`" occupy />
                        <eui-text :value="getRelatedName('rdsProviders', item)" type="name" title="供应商名称"
                            occupy />
                    </view>
                </view>
            </scroll-view>
        </view>
    </eui-popup>
    <!-- </eui-background> -->
</template>

<script setup type="ts">
import { ref, reactive, onMounted } from 'vue';
import dateRangUtil from '../../../common/dateRangUtil';
import service from '@/common/service';
import dayjs from 'dayjs';
import { getRelatedName, getWeightUnits, getDictList, getDictName, } from '../components/RelatedName.js';
import { getRdsSysConfig } from '@/hooks/init';
import { calcAtInByPt, calculatePackages, calcPtInByPtPay, calcPetpayByPtPay,validateOddLot, round } from '@/hooks/useCalculateMethod';
import { dateDiff, dateAdd, todayAdd, isDomesticBarcode } from '@/hooks/useUtils';
import { validateGds, defaultMapping, validateStores } from '@/hooks/useValidateMethod';
import { mapState, mapMutations } from 'vuex';
import { getRdsUrl, rdsRequest, rdsRequestAsync } from '@/hooks/rdsServices';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { onLoad } from "@dcloudio/uni-app";
import { set } from "vue-demi";
import { useWeightUnits } from '@/hooks/useWeightUnits'
import Enjoy from "@/common/enjoy";

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const loginStore = useLoginStore();
const sUserStore = ref('');
const { weightUnits } = useWeightUnits();

const RdsSearchBar = ref(null);
const gdsPopup = ref(null);
const providerPopup = ref(null);

const cardPtPayInput = ref(null);
const cardNInput = ref(null);

const c_sku_rec_total = ref(0);
const c_n_rec_total = ref(0);
const c_n_rec_free_total = ref(0);
const title = ref('新增收货');
const isOpened = ref('none');
const c_gcode = ref('');
const c_disabled = ref(false);
const c_status = ref('0');
const c_summary = ref("0,1,2");
const searchText = ref('');
const options = ref([
    {
        text: '删除',
        style: {
            backgroundColor: '#F56C6C',
        }
    },
]);
const inputMode = ref('2');
const inputModeRange = ref([{
    value: '1',
    text: '见物扫物',
    checked: 'true'
},
{
    value: '2',
    text: '录入数量'
},
]);
const sysConfig = ref({
    policyD: '',//永续订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyN: '',//无订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyO: '',//正常订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyP: '',//促销订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyC: '',//变价订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    ptInMinTimes: 0,//验收进价异常下限倍数
    ptInMaxTimes: 0,//验收进价异常上限倍数
    isMustInputPdt: '',//有保质期商品是否必须录入生产日期；0-否；1-是
    minExpiredPersent: 0,//允许收货的留存时间占保质期的最低百分比
    exceedOutdate: '',//保质期报警天数,生产日期+保质期距当前日期天数大于保质期报警天数则报警
    mustInputPdtExceptAdnos: [],//必须录入生产日期的例外部门
    recOverOrderRate: 0,//验收数量最多可超过订货数量比例
    canOverOrderClass: [],//验收数量可超过订货数量的品类
    productDateCtrl: 0,//生产日期控制；
    isBarcode: 0, // 0-否 1-是，默认为否，是：启用时则支持按箱码订货，否则不支持按箱码订货
    inputType: '1' // 1-件数零数分别录入方式 2-自动识别含量单值录入方式
});
const detailData = ref([]);
const delList = ref([]);
const newList = ref([]);
const modifiedList = ref([]);
const currentGds = ref({});
const currentGdsIndex = ref({});
const providerList = ref([]);
const cardNPackInput = ref(null);
const cardNOddInput = ref(null);
const cardNIptInput = ref(null);

const mainData = ref({
    c_tenant_id: '',
    c_id: '',
    c_bill_type: '701',
    c_status: '0',
    c_mk_type: '3',
    c_po_id: '',
    c_po_type: '',
    c_gmode: '',
    c_property_group: '',
    c_store_id: sUserStore.value,
    c_store_name: '',
    // c_store_name_en: defaultStoreNameEn,
    c_rec_store_type: '',
    c_wno: '00',
    c_wname: '本部',
    c_adno: '',
    c_provider: '',
    c_provider_name: '',
    c_con_type: '',
    c_con_no: '',
    c_pay_type: '',
    c_direct_buy: '0',
    c_buy_type: '0',
    c_price_type: '9',
    c_order_kind: '0',
    c_order_fast: '0',
    c_order_priv: '0',
    c_order_class: '0',
    c_d_type: '1',
    c_s_mode: '',
    c_virtual_flag: '0',
    c_rec_store_id: sUserStore.value,
    c_rec_wno: '',
    c_deliver: '',
    c_wave: '',
    c_buy_userno: '',
    c_org_no: '',
    c_charge_userno: '',
    c_rec_dt: null,
    c_rec_userno: '',
    c_rec_userno2: '',
    c_rec_processtype: '1',
    c_send_wms: '0',
    c_send_wms_dt: null,
    c_wms_id: '',
    c_fee: 0,
    c_fee_note: '',
    c_fee_id: '',
    c_fee_share: '',
    c_at_invoice: 0,
    c_invoice_provider: '',
    c_pay_cash: 0,
    c_at_opay: 0,
    c_settle_status: '0',
    c_req_pay_no: '',
    c_expect_dt: dayjs().format('YYYY-MM-DD'),
    c_end_dt: todayAdd(1, 'y'),
    c_booking_status: '0',
    c_booking_userno: '',
    c_sku_rec: 0,
    c_n_rec: 0,
    c_at_pay_rec: 0,
    c_aet_pay_rec: 0,
    c_at_in_rec: 0,
    c_at_sale_rec: 0,
    c_at_disc: 0,
    c_at_return: 0,
    c_tax_str: '',
    c_mk_store_id: sUserStore.value,
    c_mk_store_name: '',
    // c_mk_store_name_en: storeNameEn,
    c_mk_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    c_mk_userno: loginInfo.sUser,
    // c_mk_username: username,
    c_approve_status: '1',
    c_approve_dt: null,
    c_au_dt: null,
    c_au_userno: '',
    c_check_mode: '',
    c_check_dt: null,
    c_check_userno: '',
    c_print_dt: null,
    c_print_userno: '',
    c_print_n: 0,
    c_src_id: '',
    c_src_type: '',
    c_note: '',
    c_sys_note: '',
    c_rec_times: '1',
});
// isDomestic: false,
onLoad(async (option) => {
    sUserStore.value = option.storeId;
    mainData.value.c_id = option.c_id;
    mainData.value.c_store_id = option.storeId;
    mainData.value.c_rec_store_id = option.storeId;
    mainData.value.c_mk_store_id = option.storeId;
    if (option.c_id) {
        title.value = option.c_id;
        service.enjoyShowLoading('正在加载...');
        await billQuery();
        service.enjoyHideLoading();
    }
    await getSysConfig();

});

const getSysConfig = async () => {
    sysConfig.value.policyD = await getRdsSysConfig("商品验收控制参数", "永续订单验收进价控制策略");
    sysConfig.value.policyN = await getRdsSysConfig("商品验收控制参数", "无订单验收进价控制策略");
    sysConfig.value.policyO = await getRdsSysConfig("商品验收控制参数", "正常订单验收进价控制策略");
    sysConfig.value.policyP = await getRdsSysConfig("商品验收控制参数", "促销订单验收进价控制策略");
    sysConfig.value.policyC = await getRdsSysConfig("商品验收控制参数", "变价订单验收进价控制策略");
    sysConfig.value.ptInMinTimes = Number(await getRdsSysConfig("商品验收控制参数", "验收进价异常下限倍数"));
    sysConfig.value.ptInMaxTimes = Number(await getRdsSysConfig("商品验收控制参数", "验收进价异常上限倍数"));
    sysConfig.value.isMustInputPdt = await getRdsSysConfig("商品验收控制参数", "有保质期商品是否必须录入生产日期");
    sysConfig.value.minExpiredPersent = Number(await getRdsSysConfig("商品验收控制参数", "允许收货留存时间占保质期的最低百分比"));
    sysConfig.value.exceedOutdate = Number(await getRdsSysConfig("商品验收控制参数", "保质期报警天数"));
    sysConfig.value.mustInputPdtExceptAdnos = await getDictList("有保质期商品是否必须录入生产日期的例外部门");
    sysConfig.value.recOverOrderRate = Number(await getRdsSysConfig("商品验收控制参数", "验收数量最多可超过订货数量比例"));
    sysConfig.value.canOverOrderClass = await getDictList("验收数量可超过订货数量的品类");
    sysConfig.value.productDateCtrl = await getRdsSysConfig("商品验收控制参数", "是否开启生产日期控制");
    sysConfig.value.isBarcode = await getRdsSysConfig("进销存管理参数", "是否支持按箱码订货");
    sysConfig.value.isBarcode = await getRdsSysConfig("进销存管理参数", "是否支持按箱码订货");
    sysConfig.value.inputType = await getRdsSysConfig("供应链管理参数", "商品件数零数录入方式") || '1';
};
const searchConfirm = async (e) => {

    if (!e.value) {
        return;
    }
    searchText.value = e.value;

    // 检查当前机构是否为 分店或配送中心，否则不允许新建
    const result = await validateStores(
        { fieldName: 'c_store_id', newValue: sUserStore.value },
        { ischecklimit: true, firstValueMode: true }
    );
    if (!['2', '3'].includes(result.c_type)) {
        await uni.showToast({
            title: '当前机构不允许收货,请切换至分店或配送中心!',
            icon: 'none',
            duration: 3000,
        });
        await uni.navigateTo({
            url: '../modals/store/index'
        });
        return;
    }

    const serialInfo = {
        gcode: e.value,
        serialNo: '',
        sda: null,
        eda: null
    };

    const valSerialRes = await rdsRequestAsync(rdsUrl.scApi, "Rds公共服务", "ValiSerialNoRule", {
        storeId: sUserStore.value,
        serialNo: searchText.value
    })
    if (valSerialRes.HasException) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: valSerialRes.Exception.Message,
            mask: true,
        });
        return;
    } else {
        if (valSerialRes.ObjectData?.isMatchRule) {
            searchText.value = valSerialRes.ObjectData.gcode;
            serialInfo.gcode = valSerialRes.ObjectData.gcode;
            serialInfo.serialNo = e.value;
            serialInfo.sda = valSerialRes.ObjectData.sda;
            serialInfo.eda = valSerialRes.ObjectData.eda;
        }
    }

    if (!mainData.value.c_provider && detailData.value.length === 0) {
        service.enjoyShowLoading('正在加载...');
        const providerResult = await queryProviderByGcode(searchText.value);
        if (providerResult.ObjectData.length > 1) {
            providerList.value = providerResult.ObjectData
            providerPopup.value.open();
            service.enjoyHideLoading();
            return;
        }
        service.enjoyHideLoading();
    }

    let barCode = '';
    if (searchText.value.length === 7) {
        const gdsInfo = await getGdsInfo(searchText.value);
        barCode = gdsInfo.c_barcode;
    } else {
        barCode = searchText.value;
    }

    const itemIndex = detailData.value.findIndex(i => i.c_barcode === barCode);
    if (itemIndex !== -1) {
        service.enjoyShowLoading('正在加载...');
        const item = detailData.value[itemIndex];
        currentGds.value = {
            ...item,
            c_serial_no: serialInfo?.serialNo ? serialInfo?.serialNo : item.c_serial_no,
            c_product_dt: serialInfo?.sda ? serialInfo?.sda : item.c_product_dt,
            c_expired_dt: serialInfo?.eda ? serialInfo?.eda : item.c_expired_dt,
            rowType: 2
        };
        // //计算当前商品所在页数
        // const page = Math.ceil(itemIndex / 50);
        // //如果商品所在页数大于当前页数，刷新到当前页数
        // if (currentPage.value < page) {
        //     currentPage.value = page;
        // }

        //录入模式弹窗
        if (inputMode.value === '2' || mainData.value.c_status !== '0') {
            await onClickGdsInfo({
                ...detailData.value[itemIndex],
                c_serial_no: serialInfo?.serialNo ? serialInfo?.serialNo : item.c_serial_no,
                c_product_dt: serialInfo?.sda ? serialInfo?.sda : item.c_product_dt,
                c_expired_dt: serialInfo?.eda ? serialInfo?.eda : item.c_expired_dt,
                rowType: 2
            }, itemIndex)
            service.enjoyHideLoading();
            return;
        }
        const recNum = Number(currentGds.value.c_n) + Number(currentGds.value.c_order_pack);
        currentGds.value.c_n = recNum;
        const result = await calculatePackages(currentGds.value.c_order_pack, recNum);
        currentGds.value.c_n_pack = result.npack;
        currentGds.value.c_n_odd = result.odd;
        set(detailData.value, itemIndex, currentGds.value)
        await calcRowAmount(item);
        await calcMainAmount();
        service.enjoyHideLoading();
        setTimeout(() => {
            RdsSearchBar.value.clear();
        }, 300)
        return;
    }
    if (mainData.value.c_status !== '0') {
        await uni.showToast({
            title: '未查询到商品!',
            icon: 'none',
            duration: 3000,
        });
        return;
    }
    const gdsResult = await callValidateGds(serialInfo);
    if (gdsResult) {
        currentGdsIndex.value = detailData.value.findIndex(i => i.c_barcode === barCode);
        if (inputMode.value === '2') {
            // await onClickGdsInfo({
            //     ...detailData.value[currentGdsIndex.value],
            //     c_serial_no: serialInfo?.serialNo,
            //     c_product_dt: serialInfo?.sda,
            //     c_expired_dt: serialInfo?.eda,
            // }, currentGdsIndex.value)
            await onClickGdsInfo({
                ...detailData.value[currentGdsIndex.value],
            }, currentGdsIndex.value)
        }

        // setTimeout(() => {
        //     //计算当前商品所在页数
        //     const page = Math.ceil(currentGdsIndex.value / 50);
        //     //如果商品所在页数大于当前页数，刷新到当前页数
        //     if (currentPage.value < page) {
        //         currentPage.value = page;
        //     }
        // }, 300);
        await calcRowAmount(detailData.value[currentGdsIndex.value]);
        await calcMainAmount();
    }

};

const clickProviderInfo = (item, index) => {
    mainData.value.c_provider = item;
    providerPopup.value.close();
    searchConfirm({ value: searchText.value });
};

const queryProviderByGcode = async (gcode) => {
    const result = await rdsRequestAsync(rdsUrl.bcApi, "供应商引入与变更单", "GetProviderByGCode", gcode);
    if (result.HasException) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: result.Exception.Message,
            mask: true,
        });
        return;
    }
    return result;
};

const callValidateGds = async (serialInfo) => {
    currentGds.value = await initRow();
    let args = { fieldName: 'c_gcode', row: currentGds.value, newValue: searchText.value, };
    service.enjoyShowLoading('正在加载...');
    const result = await validateGds({
        url: rdsUrl.scApi, uniqueKey: '商品验收单', billType: '701', args,
        head: {
            code: mainData.value.c_store_id?.split(','),
            adno: mainData.value.c_adno,
            login_store: sUserStore.value,
            code: sUserStore.value,
            provider: mainData.value?.c_provider,
            con_no: mainData.value.c_con_no,
        },
        listManager: detailData.value,
        mapping: [
            ...defaultMapping,
            //商品信息
            ['c_od_day', 'c_od_day'],
            ['c_od_unit', 'c_od_unit'],
            //分店信息
            ['c_basic_unit', 'c_basic_unit'],
            ['c_tax_rate', 'c_tax_rate'],
            ['c_type', 'c_type'],
            ['c_unpack', 'c_unpack'],
            ['c_order_pack', 'c_order_pack'],
            ['c_order_unit', 'c_unit'],

            ['c_n_disp', 'c_dnlmt_number'],         //最佳货位量 ，字段不一致
            ['c_dnlmt_day', 'c_dnlmt_day'],         //安全库存天数
            ['c_min_to_order', 'c_n_min_order'],    //补货点，字段不一致
            ['c_n_min', 'c_n_min'],
            ['c_n_max', 'c_n_max'],
            //采购信息
            ['c_con_no', 'c_con_no'],
            ['c_provider', 'c_provider'],
            ['c_con_type', 'c_con_type'],
            ['c_pt_in', 'c_pt_in'],
            ['c_pt_pay', 'c_pt_pay'],
            ['c_pt_pay_con', 'c_pt_pay_con'],
            ['c_pet_pay', 'c_pet_pay'],
            ['c_pt_type', 'c_pt_type'],
            ['c_disc_rate', 'c_disc_rate'],
            ['c_tax_src', 'c_tax_src'],
            ['c_tax_rate_pay', 'c_tax_rate_pay'],
            ['c_deduct_rate', 'c_deduct_rate'],
            ['c_dc_store_id', 'c_dc_store_id'],
            ['c_dc_wno', 'c_dc_wno'],
            ['c_dc_ret_wno', 'c_dc_ret_wno'],
            ['c_pro_status', 'c_pro_status'],
            ['c_pt_pay_pop', 'c_pro_pt_pay'],      //促销进价（含税）,字段不一致
            ['c_pro_name', 'c_pro_name'],
            ['c_pro_period', 'c_pro_period'],
            ['c_min_order_n', 'c_min_order_n'],     //最小订量
            //商品分店信息统计信息
            ['c_lastsale_dt', 'c_lastsale_dt'],
            ['c_firstorder_dt', 'c_firstorder_dt'],
            ['c_init_disc', 'c_init_disc'],
            ['c_init_qtty', 'c_init_qtty'],
            ['c_dms', 'c_dms'],
            ['c_pdms', 'c_pdms'],
            ['c_n', 'c_n'],
            ['c_n_pack', 'c_n_pack'],
            ['c_n_odd', 'c_n_odd'],
            ['c_sn_lastweek', 'c_sn_lastweek'],     //TODO:上周销量，没有数据源

            //库存信息
            ['c_n_inv', 'c_n_inv'],                 //TODO:库存数量 没有数据源
            ['c_n_inv_bad', 'c_n_inv_bad'],         //TODO:坏货数量 没有数据源
            ['c_n_onway_in', 'c_n_onway_in'],       //TODO:入库在途数量 没有数据源
            ['c_n_onway_out', 'c_n_onway_out'],     //TODO:出库在途数量 没有数据源
            ['c_sellout_days', 'c_sellout_days'],   //TODO:可销天数=库存数量/DMS 没有数据源
            ['c_n_inv_dc', 'c_n_inv_dc'],           //TODO:配送中心库存数量 没有数据源

            ['c_serial_no', 'c_serial_no'],
            ['c_product_dt', 'c_product_dt'],
            ['c_expired_dt', 'c_expired_dt']
        ],
        initRow: await initRow,
        // allowBarcodeRepeat: false,
        // currentRow:currentGds.value,
        callback: async (items) => {
            await Promise.all(items.filter(a => !a.c_chk_msginfo).map(async item => {
                if (item.c_dc_store_id) {
                    item.c_rec_store_id = item.c_dc_store_id;
                    item.c_rec_store_name = item.c_dc_store_name;
                    item.c_rec_wno = item.c_dc_wno;
                    mainData.value.c_rec_store_id = item.c_dc_store_id;
                    mainData.value.c_rec_wno = item.c_dc_wno;
                }

                item.c_pt_pay_con = item.c_pt_pay;
                item.c_pt_pay_order = item.c_pt_pay;
                item.c_pt_type = 'C';//合同价
                //如果促销进价不为零，表示有促销进价
                if (item.c_pro_pt_pay !== 0) {
                    item.c_pt_type = 'P';//P-促销价
                    item.c_pt_pay = item.c_pro_pt_pay;
                    item.c_pet_pay = item.c_pro_pet_pay;
                    item.c_pt_in = item.c_pro_pt_in;
                }

                if (!item.c_firstorder_dt && item.c_init_disc < 100 && item.c_init_disc > 0) {
                    item.c_pt_type = 'D'//-折扣价
                    //item.c_n = item.c_init_qtty
                    item.c_pt_pay = item.c_pt_pay * item.c_init_disc * 0.01;
                    item.c_pt_in = item.c_pt_in * item.c_init_disc * 0.01;
                    item.c_pet_pay = item.c_pet_pay * item.c_init_disc * 0.01;
                }
                item.c_disc_rate = item.c_pt_pay / item.c_pt_pay_con * 100;
                item.c_order_pack = sysConfig.value.isBarcode === '1' ? (item.c_n || 1) : item.c_content;
                item.c_n = item.c_order_pack;

                const result = await calculatePackages(item.c_order_pack, item.c_n);
                item.c_n_pack = result.npack;
                item.c_n_odd = result.odd;

                //批号
                item.c_serial_no = ''
                item.c_product_dt = null;
                item.c_expired_dt = null;
                if (serialInfo && serialInfo.serialNo) {
                    item.c_serial_no = serialInfo.serialNo
                    if (serialInfo.sda || serialInfo.eda) {
                        item.c_product_dt = serialInfo.sda;
                        item.c_expired_dt = serialInfo.eda;

                        if ((item.c_od_day ?? 0) > 0) {
                            if (serialInfo.eda) {
                                // item.c_product_dt = dateAdd(1, dateAdd((item.c_od_day) * -1, serialInfo.eda, converOdUnit(item.c_od_unit)), 'd');
                                item.c_product_dt = dateAdd((item.c_od_day) * -1, serialInfo.eda, await converOdUnit(item.c_od_unit));
                            } else if (serialInfo.sda) {
                                // item.c_expired_dt = dateAdd(1, dateAdd(item.c_od_day, serialInfo.sda, converOdUnit(item.c_od_unit)))
                                item.c_expired_dt = dateAdd(item.c_od_day, serialInfo.sda, await converOdUnit(item.c_od_unit));
                            }
                        }

                        //验证 收货日期
                        if (mainData.value.c_rec_dt) {
                            if (item.c_product_dt && dayjs(mainData.value.c_rec_dt).format('YYYY-MM-DD') < dayjs(item.c_product_dt).format('YYYY-MM-DD')) {
                                item.c_chk_msginfo = `生产日期[${dayjs(item.c_product_dt).format('YYYY-MM-DD')}]不可晚于收货日期[${dayjs(mainData.value.c_rec_dt).format('YYYY-MM-DD')}]！`
                            }
                        }
                        if (item.c_product_dt && dayjs(item.c_product_dt).format('YYYY-MM-DD') > dayjs().format('YYYY-MM-DD')) {
                            item.c_chk_msginfo = `生产日期[${dayjs(item.c_product_dt).format('YYYY-MM-DD')}]不可晚于今天！`
                        }

                        if ((item.c_od_day ?? 0) > 0) {
                            const today = dayjs().format('YYYY-MM-DD');
                            //留存天数
                            const expiredDays = dateDiff(item.c_expired_dt, today);
                            // 有效期天数
                            const odDays = dateDiff(item.c_expired_dt, item.c_product_dt);

                            if (expiredDays <= 0) {
                                item.c_chk_msginfo = `商品已过保质期，不允许收货，请确认！`
                            }
                            if (item?.c_od_warning_day) {
                                if (expiredDays <= item.c_od_warning_day) {
                                    item.c_chk_msginfo = `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${item.c_od_warning_day},请确认`
                                }
                            } else {
                                if (!isNaN(minExpiredPersent) && minExpiredPersent !== 0) {
                                    if (expiredDays / odDays * 100 < minExpiredPersent) {
                                        item.c_chk_msginfo = `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）保质期占比低于最低要求${minExpiredPersent}%，请确认！`
                                    }
                                }

                                if (!isNaN(exceedOutdate) && exceedOutdate < odDays) {
                                    if (expiredDays < exceedOutdate) {
                                        item.c_chk_msginfo = `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${exceedOutdate},请确认`
                                    }
                                }
                            }
                        }
                    }
                }
            }));
            return { cancel: false }
        }
    })

    service.enjoyHideLoading();
    if (result) {
        currentGds.value = result;
        //供应商
        mainData.value.c_provider = result.c_provider;
        mainData.value.c_provider_name = result.c_provider_name;
        mainData.value.c_is_stock = result.c_is_stock;
        //合同
        mainData.value.c_con_no = result.c_con_no;
        mainData.value.c_con_type = result.c_con_type;
        mainData.value.c_pay_type = result.c_pay_type;
        mainData.value.c_d_type = result.c_d_type;
        mainData.value.c_s_mode = result.c_s_mode;
        //送货商
        mainData.value.c_deliver = result.c_deliver;

        // 如果此时 验收机构类型不是【配送中心】或者物流模式不是【直送】并且收货方式为【先收后分】，则将收货方式置为【一般收货】
        if ((mainData.value.c_rec_store_type !== '3' || mainData.value.c_d_type !== '1') && mainData.value.c_rec_processtype === '3') {
            mainData.value.c_rec_processtype = '1';
        }
    }
    return result;
}
const getGdsInfo = async (gcode) => {
    const req = {
        WhereList: [
            { c_col: "c_store_id", c_oper: "等于", c_value: mainData.value.c_store_id, c_logic: "而且" },
            { c_col: "inputOrigMode", c_logic: "而且", c_value: "1", c_oper: "等于" },
            { c_col: "c_gcode", c_oper: "等于", c_value: gcode, c_logic: "而且" }
        ]
    };
    const result = await rdsRequest(rdsUrl.bcApi, '弹窗通用查询', 'FetchComplexGds', req);
    if (result.ReturnObject.length > 0) {
        return result.ReturnObject[0]
    }
    return gcode;
}

// 选择框点击事件
const clickRight = (type) => {
    let parms = Enjoy.GetDialogParms();
    parms.CallBack = SelectionChanged;
    switch (type) {
        case 'c_wno':
            parms.SelectionType = "仓库选择";
            parms.SelectedItems = mainData.value.c_wno;
            parms.SelectionStoreId = sUserStore.value;
            break;
    }
    Enjoy.OpenDialog(parms)
}

const clear = (e) => {
    switch (e) {
        case 'c_provider':
            uni.navigateTo({
                url: '../modals/partner/index'
            });
        case 'c_product_dt':
            currentGds.value.c_product_dt = null;
            break;
        case 'c_expired_dt':
            currentGds.value.c_expired_dt = null;
            break;
    }
}

const getPtPolicy = async () => {
    let ptPolicy = ''
    const priceType = mainData.value?.c_src_type?.startsWith('5F') ? 'D' : mainData.value?.c_price_type
    //0-正常订单、1-首单折扣订单、2-可变价订单、3-促销订单、9-无订单
    switch (priceType) {
        case '0':
        case '1':
            ptPolicy = sysConfig.value.policyO;
            break;
        case '2':
            ptPolicy = sysConfig.value.policyC;
            break;
        case '3':
            ptPolicy = sysConfig.value.policyP;
            break;
        case '9':
            ptPolicy = sysConfig.value.policyN;
            break;
        case 'D':
            ptPolicy = sysConfig.value.policyD;
            break;
        default:
            ptPolicy = sysConfig.value.policyO;
            break;
    }
    if (ptPolicy === '0') {
        c_disabled.value = true;
    }
    return ptPolicy;
}
// 扫码
// const clickScanRight = async (type) => {
//     if (type === "c_gcode") {
//         if (!sUserStore.value) {
//             await uni.showToast({
//                 duration: 2000,
//                 icon: 'none',
//                 title: '请先选择机构'
//             });
//             return false;
//         }
//         await uni.scanCode({
//             success: function (res) {
//                 if (res.result !== '' && res.result !== 'undefined' && res.result !== 'null') {
//                     c_gcode.value = res.result;
//                     if (!detailData.value.length > 0) {
//                         await billListByGcode();
//                         return
//                     }
//                     const gdsList = detailData.value.filter(x => x.c_gcode === e);
//                     if (gdsList.length > 0) {
//                         currentGds.value = gdsList[0];
//                     } else {
//                         await uni.showToast({
//                             duration: 2000,
//                             icon: 'none',
//                             title: '未查询到商品'
//                         });
//                     }
//                 }
//             }
//         });
//     }
// }
const SelectionChanged = async (type, item) => {
    switch (type) {
        case 'c_store_id':
            const result = await validateStores(
                { fieldName: 'c_store_id', row: mainData.value, newValue: item.c_store_id },
                { ischecklimit: true, firstValueMode: true }
            );
            if (['2', '3'].includes(result.c_type)) {
                // 更新机构信息
                sUserStore.value = item.c_store_id;
                mainData.value.c_store_id = sUserStore.value;
                mainData.value.c_mk_store_id = sUserStore.value;
                mainData.value.c_rec_store_id = sUserStore.value;
            } else {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请选择分店或配送中心！'
                });
                await uni.navigateTo({
                    url: '../modals/store/index'
                });
            }
            break;
        case 'c_id':
            mainData.value.c_id = item.c_id;
            service.enjoyShowLoading('正在加载...');
            await billQuery();
            service.enjoyHideLoading();
            break;
        case 'c_gcode':
            c_gcode.value = item.c_gcode;
            if (!detailData.value.length > 0) {
                await billListByGcode();
                return
            }
            const gdsList = detailData.value.filter(x => x.c_gcode === c_gcode.value);
            if (gdsList.length > 0) {
                currentGds.value = gdsList[0];
                RdsSearchBar.value.clear();
            }
            break;
        case 'partner':
            mainData.value.c_provider = item.c_no;
            mainData.value.c_mk_store_id = item.c_name;
            await searchConfirm({ value: searchText.value });
            break;
    }
}

defineExpose({
    SelectionChanged
})

const onClickGdsInfo = async (item, index) => {
    currentGdsIndex.value = index;
    currentGds.value = { ...item };
    currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
    gdsPopup.value.open('bottom');
    // const isDomestic = isDomesticBarcode(currentGds.value.c_barcode);
    // if (isDomestic) {
    //     c_disabled.value = true
    //     // await $refs.productDtRef.getFocus();
    // } else {
    //     c_disabled.value = false
    //     // await $refs.expiredDtRef.getFocus();
    // }
};
const validateDetail = async (args) => {
    const { type, fieldName, oldValue, newValue, itemIndex } = args;
    let result = null;
    let overResult = null;
    let validateWeightUnitsResult = null;
    let c_n;
    let validateResult;

    switch (fieldName) {
        case 'c_pt_pay':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数'
                });
                currentGds.value.c_pt_pay = 0;
                cardPtPayInput.value.inputValue = 0;
                return;
            }
            currentGds.value.c_pt_pay = parseFloat(newValue).toFixed(2);
            const pt_pay = newValue
            //0-不可更改，1-可改低，2-可任意修改
            const ptPolicy = await getPtPolicy();
            if (ptPolicy === '0') {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '结算价不允许调整'
                });
                currentGds.value.c_pt_pay = oldValue || 0;
                cardPtPayInput.value.inputValue = oldValue || 0;
                break;
            } else if (ptPolicy === '1' && newValue > oldValue) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '结算价不允许调高'
                });

                currentGds.value.c_pt_pay = oldValue || 0;
                cardPtPayInput.value.inputValue = oldValue || 0;
                cardPtPayInput.value.getFocus()
                break;
            }
            if (sysConfig.value.ptInMaxTimes !== 0) {
                if (pt_pay > currentGds.value.c_pt_pay_con * sysConfig.value.ptInMaxTimes) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: `当前结算价与合同结算价相比，超出上限倍数[${sysConfig.value.ptInMaxTimes}]的限制！`
                    });
                    currentGds.value.c_pt_pay = oldValue || 0;
                    cardPtPayInput.value.inputValue = oldValue || 0;
                    cardPtPayInput.value.getFocus()
                    break;
                }
            }
            if (sysConfig.value.ptInMinTimes !== 0) {
                if (pt_pay < currentGds.value.c_pt_pay_con / sysConfig.value.ptInMinTimes) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: `当前结算价与合同结算价[${currentGds.value.c_pt_pay_con}]相比，低于下限倍数[${sysConfig.value.ptInMinTimes}]的限制！`
                    });
                    cardPtPayInput.value.getFocus()
                    break;
                }
            }
            currentGds.value.c_pt_pay = pt_pay
            currentGds.value.c_pt_in = calcPtInByPtPay(
                {
                    c_pt_pay: pt_pay,
                    c_tax_rate: currentGds.value.c_tax_rate,
                    c_tax_rate_pay: currentGds.value.c_tax_rate_pay,
                    c_tax_src: currentGds.value.c_tax_src
                })
            currentGds.value.c_pet_pay = calcPetpayByPtPay({
                c_pt_pay: pt_pay,
                c_tax_rate_pay: currentGds.value.c_tax_rate_pay,
                c_tax_src: currentGds.value.c_tax_src
            });
            await calcRowAmount();
            break;
        case 'c_n_pack':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数！'
                });
                currentGds.value.c_n_pack = 0;
                setTimeout(() => {
                    cardNPackInput.value.getFocus()
                }, 300);
                return
            }
            currentGds.value.c_n_pack = parseInt(newValue);
            c_n = currentGds.value.c_n_pack * currentGds.value.c_order_pack + currentGds.value.c_n_odd;
            currentGds.value.c_n_input = round(c_n / currentGds.value.c_order_pack, 3);
            currentGds.value.c_n = c_n;
            overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, c_n,)
            if (!overResult) {
                // currentGds.value.c_n_pack = oldValue;
                // cardNPackInput.value.inputValue = oldValue;
                setTimeout(() => {
                    cardNPackInput.value.getFocus()
                }, 300);
                return
            }
            await calcRowAmount(currentGds.value);
            break;
        case 'c_n_odd':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数！'
                });
                currentGds.value.c_n_odd = 0;
                setTimeout(() => {
                    cardNOddInput.value.getFocus()
                }, 300);
                return
            }
            currentGds.value.c_n_odd = newValue;
            validateWeightUnitsResult = await validateWeightUnits(newValue);
            if (!validateWeightUnitsResult) {
                setTimeout(() => {
                    cardNOddInput.value.getFocus()
                }, 300);
                return;
            }
            validateResult = validateOddLot(newValue, currentGds.value.c_n_pack, currentGds.value.c_order_pack, '1');
            result = validateResult.result;
            if (!result || result?.validated) {
                currentGds.value.c_n = validateResult.n;
                currentGds.value.c_n_pack = validateResult.npack;
                currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_order_pack, 3);
                if (validateResult.result) {
                    currentGds.value.c_n_odd = validateResult.result?.retValue;
                }
                overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, validateResult.n,)
                if (!overResult) {
                    // currentGds.value.c_n_odd = 0;
                    // cardNOddInput.value.inputValue = oldValue;
                    setTimeout(() => {
                        cardNOddInput.value.getFocus()
                    }, 300);
                    return
                }
                await calcRowAmount(currentGds.value);
            } else {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: result?.message
                });
                // currentGds.value.c_n_odd = oldValue;
                // cardNOddInput.value.inputValue = oldValue;
                setTimeout(() => {
                    cardNOddInput.value.getFocus()
                }, 300);
            }
            break;
        case 'c_n_input':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数！'
                });
                currentGds.value.c_n_input = 0;
                setTimeout(() => {
                    cardNIptInput.value.getFocus()
                }, 300);
                return
            }

            const c_n_odd = round(newValue * currentGds.value.c_order_pack, 3);
            validateResult = validateOddLot(c_n_odd, currentGds.value.c_n_pack, currentGds.value.c_order_pack, '1', true);
            result = validateResult.result;
            if (!result || result?.validated) {
                // 在赋值之前判断零数是否为小数
                validateWeightUnitsResult = await validateWeightUnits(result?.retValue);
                if (!validateWeightUnitsResult) {
                    setTimeout(() => {
                        cardNIptInput.value.getFocus()
                    }, 300);
                    return;
                }
                if (result) {
                    currentGds.value.c_n_odd = result.retValue;
                }

                currentGds.value.c_n = validateResult.n;
                currentGds.value.c_n_pack = validateResult.npack;
                currentGds.value.c_n_input = newValue;

                overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, validateResult.n,)
                if (!overResult) {
                    setTimeout(() => {
                        cardNIptInput.value.getFocus()
                    }, 300);
                    return
                }
                await calcRowAmount(currentGds.value);
            } else {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: result?.message
                });
                setTimeout(() => {
                    cardNIptInput.value.getFocus()
                }, 300);
            }
            break;
        case 'c_n':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数'
                });
                currentGds.value.c_n = 0;
                cardNInput.value.getFocus();
                return;
            }
            currentGds.value.c_n = newValue;
            const recN = newValue;
            validateWeightUnitsResult = await validateWeightUnits(newValue);
            if (!validateWeightUnitsResult) {
                currentGds.value.c_n = oldValue;
                cardNInput.value.inputValue = oldValue;
                cardNInput.value.getFocus();
                return;
            }
            overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, recN,)
            if (!overResult) {
                cardNInput.value.getFocus()
                return
            }
            result = await calculatePackages(currentGds.value.c_order_pack, recN);
            currentGds.value.c_n_pack = result.npack;
            currentGds.value.c_n_odd = result.odd;
            currentGds.value.c_n_input = round(newValue / currentGds.value.c_order_pack, 3);
            await calcRowAmount();
            break;
        case 'c_n_free':
            if (newValue < 0 || newValue > 999999) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '请输入0~999999的数'
                });
                currentGds.value.c_n_free = 0;
                return;
            }
            currentGds.value.c_n_free = newValue;
            await calcRowAmount();
            break;
    }
}
const validateWeightUnits = async (recN) => {
    if (!weightUnits.value.includes(currentGds.value.c_order_unit)) {
        if (recN % 1 > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '本商品验收数量不允许录入小数，仅重量单位商品可以录入小数'
            });
            return false;
        }
    }
    return true;
};
const buttonClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'submit':
            // 保存
            if (detailData.value.length <= 0) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '商品不能为空！'
                });
                return;
            }
            service.enjoyShowLoading('正在保存...');
            const saveResult = await saveBill();
            if (saveResult) {
                await billQuery();
            }
            service.enjoyHideLoading();
            break;
        case 'audit':
            // 审核
            if (detailData.value.length <= 0) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '商品不能为空！'
                });
                return;
            }

            if (mainData.value.c_status === '0') {
                await uni.showModal({
                    title: ' 提示',
                    content: '请确认，审核单据吗?',
                    showCancel: true,
                    success: async (res) => {
                        if (res.confirm) {
                            const saveResult = await saveBill();
                            if (!saveResult) {
                                return;
                            }
                            const req = {
                                BillId: mainData.value.c_id,
                                UserNo: loginInfo.sUser,
                            }
                            service.enjoyShowLoading('正在审核...');
                            const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillAudit', req, '701');
                            service.enjoyHideLoading();
                            await uni.showToast({
                                duration: 2000,
                                icon: 'none',
                                title: ' 审核成功！'
                            });
                            await billQuery();
                        }
                    }
                });
            }
            break;
        case 'cancel':
            gdsPopup.value.close()
            RdsSearchBar.value.searchClick();
            break;
        case 'submit3':
            // if (c_disabled.value) {
            //     if (!await validateProductDt(currentGds.value.c_product_dt)) {
            //         return;
            //     }
            // } else {
            //     if (!await validateExpiredDt(currentGds.value.c_expired_dt)) {
            //         return;
            //     }
            // }
            if (sysConfig.value.isMustInputPdt === '1' &&//参数：有保质期商品是否必须录入生产日期
                currentGds.value.c_od_day > 0 &&//保质期大于0
                !currentGds.value.c_product_dt &&//生产日期为空
                (currentGds.value.c_n_free > 0 || //赠品收获数量
                    currentGds.value.c_n > 0) &&//收货数量
                !sysConfig.value.mustInputPdtExceptAdnos.some(adno => currentGds.value.c_adno.startsWith(adno.value)) //排除例外部门的
            ) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '商品有保质期管理，请录入生产日期'
                });
                return;
            }

            // 验证 生产日期是否早于历史验收的生产日期
            if (sysConfig.value.productDateCtrl == '1' || sysConfig.value.productDateCtrl == '2') {
                // 供应商、商品、生产日期
                const rep = await rdsRequestAsync(rdsUrl.scApi, '商品验收单', 'QueryRecGaByCodePrv', { gcode: currentGds.value.c_gcode, provider: mainData.value.c_provider }, 'S01');
                if (rep.HasException) {
                    await uni.showToast({
                        duration: 2500,
                        icon: 'none',
                        title: rep.Exception.Message
                    });
                    return;
                }
                if (rep.ObjectData && rep.ObjectData?.c_product_dt && currentGds.value.c_product_dt < dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')) {
                    await uni.showToast({
                        duration: 2500,
                        icon: 'none',
                        title: `商品生产日期[${dayjs(currentGds.value.c_product_dt).format('YYYY-MM-DD')}]早于本商品在验收单[${rep.ObjectData.c_id}]的生产日期[${dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')}]!`
                    });
                    if (sysConfig.value.productDateCtrl === '2') {
                        return;
                    }
                }
            }

            service.enjoyShowLoading("正在加载...");
            currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
            set(detailData.value, currentGdsIndex.value, currentGds.value)
            try {
                await saveBill();
                await billQuery();
            } catch (error) {
                console.log("error", error)
                service.enjoyHideLoading();
            }

            gdsPopup.value.close();
            service.enjoyHideLoading();
            await calcMainAmount();
            RdsSearchBar.value.clear();
            break;
    }
};
// 获取订货单单据列表信息
const billListByGcode = async () => {
    service.enjoyShowLoading('正在加载...');
    const req = {
        WhereList: [
            { c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            { c_col: "c_status", c_oper: "等于", c_value: '0', c_logic: "而且" },
            { c_col: "c_po_type", c_oper: "为空", c_value: '', c_logic: "而且" },
            { c_col: "c_po_id", c_oper: "为空", c_value: '', c_logic: "而且" },
        ]
    };
    if (searchText.value) {
        req.WhereList.push({
            c_col: "c_gcode",
            c_oper: "等于",
            c_value: searchText.value,
            c_logic: "而且",
        });
    }
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyQueryList', req, '701');
    var _data = result.ReturnObject;
    if (_data.length === 1) {
        mainData.value = _data[0];
        await billQuery();
    } else if (_data.length > 1) {
        await uni.navigateTo({
            url: '../modals/recOrder/index?storeId=' + sUserStore.value + "&orderData=" + JSON.stringify(_data)
        });
    } else {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '未查询到数据',
            mask: true,
        });
    }
    service.enjoyHideLoading();
}
// 获取单据详情信息
const billQuery = async () => {

    if (!mainData.value.c_id) {
        return;
    }
    const req = {
        BillId: mainData.value.c_id,
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillQuery', req, '701');
    if (result.ds.length > 0) {
        mainData.value = result.ds[0];
        detailData.value = result.ds1;
        detailData.value.forEach(x => {
            x.rowType = 0;
        })
        title.value = mainData.value.c_id + '详情';
        c_sku_rec_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n > 0 || current.c_n_free > 0), 0);
        c_n_rec_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
        c_n_rec_free_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_free ?? 0), 0);
    }

}
// 保存数据
const saveBill = async () => {
    // let productDtGds = [];
    // let excludeDtGds = [];
    // let warnMessage = '';
    // detailData.value.forEach((x, index) => {
    //     const isDomestic = isDomesticBarcode(x.c_barcode);
    //     if (isDomestic) {//国内码
    //         if (!x.c_product_dt) {
    //             productDtGds.push(index + 1)
    //         }
    //     } else {//国外码
    //         if (!x.c_expired_dt) {
    //             excludeDtGds.push(index + 1)
    //         }
    //     }
    // })
    // if (productDtGds.length > 0) {
    //     warnMessage += `商品第${productDtGds.join(',')}行未录入生产日期`;
    // }
    // if (excludeDtGds.length > 0) {
    //     warnMessage += `商品第${excludeDtGds.join(',')}行未录入限用日期`;
    // }
    // if (warnMessage !== '') {
    //     await uni.showToast({
    //         duration: 2000,
    //         icon: 'none',
    //         title: warnMessage
    //     });
    //     return;
    // }
    //验证生产日期
    const validateResult = await validateProduceDt()
    if (!validateResult.validated) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: validateResult.msg
        });
        return false;
    }
    const flag = mainData.value.c_id;
    if (!mainData.value.c_id) {
        const getBillIdReq = {
            BillIdKeyValue: {
                key: "c_id",
                value: ""
            },
            BillVariable: "",
            TableName: "tb_io_rec",
            BillName: "商品验收单"
        }
        const billId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBillIdReq, '701');
        if (billId) {
            mainData.value.c_mk_userno = loginInfo.sUser;
            mainData.value.c_mk_store_id = sUserStore.value;
            mainData.value.c_id = billId;
            title.value = billId;
        }
    } else {
        mainData.value.c_modify_userno = loginInfo.sUser;
        mainData.value.c_modify_dt = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }

    detailData.value.forEach(x => x.c_id = mainData.value.c_id)
    newList.value = detailData.value.filter(x => x.rowType === 1);
    modifiedList.value = detailData.value.filter(x => x.rowType === 2);
    const req = {
        NewList: flag ? [] : [mainData.value],
        ModifiedList: flag ? [mainData.value] : [],
        DelList: [],
        TableName: "tb_io_rec",
        PrimaryKeys: ["c_tenant_id", "c_id"],
        ChildData: [{
            ChildTableName: "tb_io_rec_g",
            ParentTableName: "tb_io_rec",
            ChildColumnNames: ["c_id"],
            ParentColumnNames: ["c_id"],
            ChildSaveModel: {
                NewList: newList.value,
                ModifiedList: modifiedList.value,
                DelList: delList.value,
                TableName: "tb_io_rec_g",
                PrimaryKeys: ["c_tenant_id", "c_id", "c_gsort"],
                //Cloumns: ["c_id", "c_tenant_id", "c_gsort", "c_n_free", "c_at_pay", "c_n_pack", "c_n_odd", "c_n", "c_n_free", "c_at_pay", "c_aet_pay", "c_at_in", "c_at_sale", "c_product_dt", "c_expired_dt", "c_rec_status", "c_rec_userno", "c_note"],
            },
        }],
        BillSet: {
            BillIdKeyValue: {
                key: "c_id",
                value: mainData.value.c_id
            },
            BillVariable: "",
            TableName: "tb_io_rec",
            BillName: "商品验收单"
        },
    };
    const result = await rdsRequestAsync(rdsUrl.scApi, '商品验收单', 'EnjoyBillSaveNew', req, '701');
    if (result.HasException) {
        if (!flag) {
            mainData.value.c_id = '';
        }
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: result.Exception.Message
        });
        return false;
    } else {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: `保存成功`
        });
        newList.value = [];
        modifiedList.value = [];
        delList.value = [];
        return true;
    }

}
const canOverOrderValidate = async (ccode, orderN, recN) => {
    if (mainData.value.c_price_type !== '9' && recN > orderN) {
        //是否可超收的品类
        if (sysConfig.value.canOverOrderClass.some(c => ccode.startsWith(c.value) || c.value.startsWith(ccode))) {
            const rate = isNaN(sysConfig.value.recOverOrderRate) ? 0 : sysConfig.value.recOverOrderRate;
            const maxN = (orderN * (1 + rate * 0.01)).toFixed(3);
            if (recN > maxN) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `验收数量超过允许的超收比例${sysConfig.value.recOverOrderRate}%，订货数量${orderN} 验收数量${recN},最多可验收数量${maxN}`
                });
                return false;
            }
        } else {
            await uni.showToast({
                duration: 3000,
                icon: 'none',
                title: `不允许超订单数量验收,订货数量${orderN} 验收数量${recN}`
            });
            return false;
        }
    }
    return true;
}
/**
 * 计算当前金额
 */
const calcRowAmount = async () => {

    currentGds.value.c_at_pay = calcAtInByPt({ c_pt: currentGds.value.c_pt_pay, c_n: currentGds.value.c_n });
    currentGds.value.c_at_in = calcAtInByPt({ c_pt: currentGds.value.c_pt_in, c_n: currentGds.value.c_n });
    currentGds.value.c_aet_pay = calcAtInByPt({ c_pt: currentGds.value.c_pet_pay, c_n: currentGds.value.c_n });
    currentGds.value.c_at_sale = calcAtInByPt({ c_pt: currentGds.value.c_price, c_n: currentGds.value.c_n });
}
const calcMainAmount = async () => {
    mainData.value.c_sku_rec = detailData.value.filter(i => i.c_n > 0 || i.c_n_free > 0).map(i => i.c_gcode).reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], []).length;
    mainData.value.c_n_rec = detailData.value.reduce((pre, current) => pre + (Number(current.c_n) ?? 0) + (Number(current.c_n_free) ?? 0), 0);
    mainData.value.c_at_pay_rec = detailData.value.reduce((pre, current) => pre + current.c_at_pay, 0);
    mainData.value.c_aet_pay_rec = detailData.value.reduce((pre, current) => pre + current.c_aet_pay, 0);
    mainData.value.c_at_in_rec = detailData.value.reduce((pre, current) => pre + current.c_at_in, 0);
    mainData.value.c_at_sale_rec = detailData.value.reduce((pre, current) => pre + current.c_at_sale, 0);
    c_sku_rec_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n > 0 || current.c_n_free > 0), 0);
    c_n_rec_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
    c_n_rec_free_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_free ?? 0), 0);
}
const converOdUnit = async (odUnit) => {

    let unit = 'd';
    switch (odUnit) {
        case 'D':
            unit = 'd'
            break;
        case 'M':
            unit = 'M'
            break;
        case 'Y':
            unit = 'y'
            break;
    }
    return unit
}
// 切换录入方式
const toggleMode = async (value) => {

    inputMode.value = value;
}
const validateProductDate = async (productDt) => {

    //如果保质期大于0
    if ((currentGds.value.c_od_day ?? 0) > 0) {
        //到期日期
        let expiredDt = dateAdd(currentGds.value.c_od_day, productDt, await converOdUnit(currentGds.value.c_od_unit))
        expiredDt = dateAdd(-1, expiredDt);

        const today = dayjs().format('YYYY-MM-DD');
        //留存天数
        const expiredDays = dateDiff(expiredDt, today);
        if (expiredDays <= 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '商品已过保质期，不允许收货，请确认！'
            });
            return false;
        }
        if (!isNaN(sysConfig.value.minExpiredPersent) && sysConfig.value.minExpiredPersent !== 0) {
            if (expiredDays / currentGds.value.c_od_day * 100 < sysConfig.value.minExpiredPersent) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）保质期占比低于最低要求${sysConfig.value.minExpiredPersent}%，请确认！`
                });
                return false;
            }
        }
        if (!isNaN(sysConfig.value.exceedOutdate) && sysConfig.value.exceedOutdate < currentGds.value.c_od_day) {
            if (expiredDays < sysConfig.value.exceedOutdate) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${sysConfig.value.exceedOutdate},请确认`
                });
                return false;
            }
        }
        currentGds.value.c_expired_dt = expiredDt;
        currentGds.value.c_product_dt = productDt;
    }
    return true;
}
const productDtChanged = async (value, index) => {
    const result = await validateProductDt(value);
    if (!result) {
        currentGds.value.c_product_dt = null;
    }
}
const expiredDtChanged = async (value, index) => {
    const result = await validateExpiredDt(value);
    if (!result) {
        currentGds.value.c_expired_dt = null;
    }
}
const validateProductDt = async (value) => {
    if (!value) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '生产日期不能为空！'
        });
        return false;
    }
    const productDt = value;
    const today = dayjs().format('YYYY-MM-DD');
    if (mainData.value.c_rec_dt) {
        if (mainData.value.c_rec_dt < productDt) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不可晚于收货日期!'
            });
            return false;
        }
    } else {
        if (dateDiff(productDt, today) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不能晚于今天!'
            });
            return false;
        }
    }
    if ((currentGds.value.c_od_day ?? 0) === 0) {
        if (currentGds.value.c_expired_dt && dateDiff(productDt, currentGds.value.c_expired_dt) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '限用日期不能早于生产日期!'
            });
            return false;
        }
    }
    console.log("sysConfig.value.productDateCtrl", sysConfig.value.productDateCtrl)
    // 验证 生产日期是否早于历史验收的生产日期
    if (sysConfig.value.productDateCtrl == '1' || sysConfig.value.productDateCtrl == '2') {
        // 供应商、商品、生产日期
        const rep = await rdsRequestAsync(rdsUrl.scApi, '商品验收单', 'QueryRecGaByCodePrv', { gcode: currentGds.value.c_gcode, provider: mainData.value.c_provider }, 'S01');
        if (rep.HasException) {
            await uni.showToast({
                duration: 2500,
                icon: 'none',
                title: rep.Exception.Message
            });
            return false;
        }
        if (rep.ObjectData && rep.ObjectData?.c_product_dt && productDt < dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')) {
            await uni.showToast({
                duration: 2500,
                icon: 'none',
                title: `商品生产日期[${productDt}]早于本商品在验收单[${rep.ObjectData.c_id}]的生产日期[${dayjs(rep.ObjectData?.c_product_dt).format('YYYY-MM-DD')}]!`
            });
            if (sysConfig.value.productDateCtrl === '2') {
                return false;
            }
        }
    }

    const result = await validateProductDate(productDt)
    return result;
}
const validateExpiredDt = async (value) => {
    // if (!value) {
    //     await uni.showToast({
    //         duration: 2000,
    //         icon: 'none',
    //         title: '限用日期不能为空！'
    //     });
    //     return false;
    // }
    const today = dayjs().format('YYYY-MM-DD');
    const expiredDt = value;
    if (today > expiredDt) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '限用日期不能早于今天!'
        });
        return false;
    }
    if ((currentGds.value.c_od_day ?? 0) === 0) {
        if (currentGds.value.c_product_dt && dateDiff(currentGds.value.c_product_dt, expiredDt) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不能晚于限用日期!'
            });
            return false;
        }
    }
    if (currentGds.value.c_od_day) {
        let productDt = dateAdd(1, dateAdd((currentGds.value.c_od_day) * -1, expiredDt, await converOdUnit(currentGds.value.c_od_unit)), 'd');
        if (mainData.value.c_rec_dt) {
            if (productDt > mainData.value.c_rec_dt) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: `商品生产日期不可晚于收货！根据商品保质期反算生产日期为[${productDt}]！`
                });
                return false;
            }
        } else if (productDt > today) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: `商品生产日期不可晚于今天！根据商品保质期反算生产日期为[${productDt}]！`
            });
            return false;
        }
        const result = await validateProductDate(productDt)
        // if (!result) {
        // 	currentGds.value.c_expired_dt = '';
        // }
        return result
    }
    return true;
}
/**
 * 验证保质期大于0的商品(有收获数量的商品)，生产日期必填（例外部门除外）
 */
const validateProduceDt = async () => {

    let validated = true;
    let msg = ''

    let mustInputPdtGcodes = []
    let mustInputPdtIds = []
    detailData.value.forEach(i => {
        //重置错误信息
        if (i.c_err_msg) {
            i.c_err_msg = null;
        }
        if (sysConfig.value.isMustInputPdt === '1' &&//参数：有保质期商品是否必须录入生产日期
            i.c_od_day > 0 &&//保质期大于0
            !i.c_product_dt &&//生产日期为空
            (i.c_n_free > 0 || //赠品收获数量
                i.c_n > 0) &&//收货数量
            !sysConfig.value.mustInputPdtExceptAdnos.some(adno => i.c_adno.startsWith(adno.value)) //排除例外部门的
        ) {
            const err = [{ c_msg_err: '商品有保质期管理，请录入生产日期' }]
            i.c_err_msg = JSON.stringify(err)
            mustInputPdtIds.push(i.c_id);
            mustInputPdtGcodes.push(i.c_gcode);
        }
    });

    const strGcode = mustInputPdtGcodes.join(',');
    if (strGcode) {
        msg = `保存失败！以下商品有保质期管理，请录入生产日期！商品编码：${strGcode}`;
        validated = false;
    }

    return { validated, msg };
}

const initRow = async (index) => {
    const sort = Math.max(0, ...detailData.value.map(f => f.c_gsort)) + 1 + (index || 0);
    return {
        c_tenant_id: '',
        c_id: '',
        c_gsort: sort,
        c_gcode: '',
        c_gname: '',
        c_barcode: '',
        c_type: '',
        c_adno: '',
        c_ccode: '',
        c_bcode: '',
        c_order_unit: '',
        c_order_pack: 0,
        c_tax_src: '',
        c_tax_rate_pay: 0,
        c_tax_rate: 0,
        c_pt_pay_con: 0,
        c_pt_pay_pop: 0,
        c_disc_rate: 0,
        c_pt_pay: 0,
        c_pet_pay: 0,
        c_pt_in: 0,
        c_pt_fall: 0,
        c_price: 0,
        c_deduct_rate: 0,
        c_pt_type: '',
        c_n_order: 0,
        c_n_free_order: 0,
        c_n_confirm: 0,
        c_n_free_confirm: 0,
        c_at_pay_order: 0,
        c_aet_pay_order: 0,
        c_at_in_order: 0,
        c_at_sale_order: 0,
        c_request: '',
        c_n_pack: 0,
        c_n_odd: 0,
        c_n: 0,
        c_n_free: 0,
        c_at_pay: 0,
        c_aet_pay: 0,
        c_at_in: 0,
        c_at_sale: 0,
        c_at_disc: 0,
        c_at_return: 0,
        c_invoice_rate: 0,
        c_od_day: 0,
        c_od_unit: '',
        c_product_dt: null,
        c_expired_dt: null,
        c_serial_no: '',
        c_rec_status: '',
        c_rec_userno: '',
        c_reject_reason: '',
        c_pro_status: '',
        c_pro_name: '',
        c_pro_period: '',
        c_fee: 0,
        c_src_id: '',
        c_src_type: '',
        c_note: '',
        c_gds_flag: '',
        c_err_msg: '',
        rowType: 1,
        c_dc_store_id: '',
        c_provider: '',
        c_is_stock: '',
        c_con_no: '',
        c_con_type: '',
        c_pay_type: '',
        c_d_type: '',
        c_s_mode: '',
        c_deliver: '',
    }
}
const change = async (e) => {
    isOpened.value = e;
    console.log('返回：', e);
}
const bindClick = async (e, index) => {
    console.log("e,index", e, index);
    await uni.showModal({
        title: ' 提示',
        content: '您确定要删除数据吗？',
        showCancel: true,
        success: async (res) => {
            if (res.confirm) {
                delList.value.push(detailData.value[index]);
                detailData.value.splice(index, 1);
                await calcMainAmount();
            }
        }
    });
}
</script>

<style lang="scss" scoped>
@import '@/static/font/enjoyicon/iconfont.css';
@import '@/main.scss';

::v-deep .white-main {
    margin: 20rpx 0;
}

.content-img {
    background-color: #FFFFFF;
    background-size: 100% 176rpx;
    background-repeat: no-repeat;
    width: 100%;
}

.custom-menu {
    // border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    justify-content: flex-start;
}

.setting-item {
    display: flex;
    align-items: center;
    flex-direction: row;
    font-size: 0.8em;
    margin: 0.5em;
    padding: 0.5em;
}

.setting-desc {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex: 1;
    width: 100%;
    font-size: 0.8em;
    // margin: 0;
    padding: 0.5em;
}

.extra-view {
    margin-right: 30rpx;
    font-size: 12px;
    color: #0099ff
}

.bt-button {
    background-color: #FFFFFF;
    padding: 10rpx 0rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// 业务自定义
.icon_new_count {
    color: #00aaff;
}

.top-view {
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
}

.footer-view {
    width: 100%;
    flex: 1;
}

.m-main-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    font-size: 12px;
}

.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    border-bottom: 1px solid $uni-border-color;
    font-size: 12px;
}

.popup-content {
    align-items: center;
    justify-content: flex-start;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    // height: 600rpx;
    // overflow-y: scroll;
}


.image-min {
    width: 100%;
    height: 150rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
    margin-top: -20rpx;
}

.popup-height {
    width: 200px;
}

.popup-content-message {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
    width: 100%;
    height: 84rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: $uni-text-color-secondary;
    font-size: $uni-font-size-level1;
    line-height: 45rpx;
    text-align: center;
    position: relative;
}
</style>
